const router = require("koa-router")();
const UserModel = require("../../models/user");
const { mongoList } = require("../../static/data");
const ShoesModel = require("../../models/shoesList");
router.post("/api/history", async ctx => {
    let { userID, shoesID, state } = ctx.request.body;
    // 通过id查鞋子,查到了放在shoesRes里面
    var shoesRes;
    for (let m of mongoList) {
        shoesRes = await ShoesModel(m).find({ _id: shoesID });
        // 搜到了就跳出循环
        if (shoesRes.length != 0) {
            break;
        }
    }
    if (state) {
        // 历史记录true为添加历史记录
        // 查看是否已经在历史记录中
        var res = await UserModel.find({ _id: userID });
        var data = res[0]
        var ifHave = data.history.filter((res) => {
            if (String(res._id) == String(shoesRes[0]._id)) {
                return true
            } else {
                return false
            }
        })
        if (ifHave.length == 0) {
            // 历史记录不存在
            await UserModel.findOneAndUpdate({ _id: userID }, {
                $push: { history: shoesRes[0] }
            });
        } else {
            // 历史记录已经存在就，先删除，再重新添加，为了列表的顺序
            await UserModel.updateOne({ _id: userID }, { $pull: { history: { _id: shoesID } } });
            await UserModel.findOneAndUpdate({ _id: userID }, {
                $push: { history: shoesRes[0] }
            });
        }
    }else{
        await UserModel.updateOne({_id: userID},{$pull:{history:{_id:shoesID}}})
    }
    ctx.body = {
        code: 200,
        msg: `更新历史记录!`
    }
})
module.exports = router;